// 二维码分享功能注入脚本
(function() {
    'use strict';
    
    // 防止重复注入
    if (window.qrCodeShareInitialized) return;
    window.qrCodeShareInitialized = true;
    
    // 配置常量
    const CONFIG = {
        iconSize: 48,
        panelWidth: 280,
        panelHeight: 350,
        animationDuration: 300,
        zIndex: 10000,
        storageKey: 'qrShareIconPosition',
        defaultPosition: { 
            topPercent: 30,     // 距顶部30%
            rightPercent: 5     // 距右边5%
        },
        // 路径转换规则配置
        pathRules: {
            // 启用路径转换
            enabled: true,
            // 转换规则列表
            rules: [
                // 规则1: /page/xxx -> /m/page/xxx
                {
                    match: '/page/*',           // 匹配模式
                    transform: '/m/page/*'      // 转换目标
                },
                // 规则2: /data-app/mobile/app/xxx -> /m/app/xxx
                {
                    match: '/data-app/mobile/app/*',
                    transform: '/m/app/*'
                },
                // 可以添加更多规则
                // {
                //     match: '/admin/*',
                //     transform: '/m/admin/*'
                // }
            ]
        }
    };
    
    // 路径匹配和转换工具函数
    const PathTransformer = {
        // 检查当前路径是否应该显示二维码
        shouldShowQRCode() {
            if (!CONFIG.pathRules.enabled) {
                return true;
            }
            
            const currentPath = window.location.pathname;
            
            // 检查是否匹配任何转换规则
            for (const rule of CONFIG.pathRules.rules) {
                if (this.matchPattern(currentPath, rule.match)) {
                    return true;
                }
            }
            
            return false;
        },
        
        // 转换URL路径
        transformURL(originalURL) {
            try {
                const url = new URL(originalURL);
                const currentPath = url.pathname;
                
                if (!CONFIG.pathRules.enabled) {
                    return originalURL;
                }
                
                // 查找匹配的转换规则
                for (const rule of CONFIG.pathRules.rules) {
                    if (this.matchPattern(currentPath, rule.match)) {
                        const transformedPath = this.transformPath(currentPath, rule.match, rule.transform);
                        if (transformedPath !== currentPath) {
                            url.pathname = transformedPath;
                            const transformedURL = url.toString();
                            return transformedURL;
                        }
                    }
                }
                
                return originalURL;
            } catch (error) {
                console.error('URL转换失败:', error);
                return originalURL;
            }
        },
        
        // 匹配路径模式（支持通配符*）
        matchPattern(path, pattern) {
            if (pattern.includes('*')) {
                // 将通配符转换为正则表达式
                const regexPattern = pattern
                    .replace(/[.+^${}()|[\]\\]/g, '\\$&')  // 转义特殊字符
                    .replace(/\*/g, '(.*)');                // * 替换为捕获组
                const regex = new RegExp('^' + regexPattern + '$');
                return regex.test(path);
            } else {
                // 精确匹配
                return path === pattern;
            }
        },
        
        // 转换路径
        transformPath(originalPath, matchPattern, transformPattern) {
            if (!matchPattern.includes('*') || !transformPattern.includes('*')) {
                // 简单替换，不支持通配符
                return transformPattern;
            }
            
            // 提取通配符匹配的部分
            const regexPattern = matchPattern
                .replace(/[.+^${}()|[\]\\]/g, '\\$&')
                .replace(/\*/g, '(.*)');
            const regex = new RegExp('^' + regexPattern + '$');
            const match = originalPath.match(regex);
            
            if (!match) {
                return originalPath;
            }
            
            // 替换转换模式中的通配符
            let result = transformPattern;
            for (let i = 1; i < match.length; i++) {
                result = result.replace('*', match[i]);
            }
            
            return result;
        }
    };
    
    // 样式模板
    const STYLES = `
        .qr-share-container {
            position: fixed;
            z-index: ${CONFIG.zIndex};
            user-select: none;
            pointer-events: auto;
        }
        
        .qr-icon {
            width: ${CONFIG.iconSize}px;
            height: ${CONFIG.iconSize}px;
            background: linear-gradient(135deg, #4CAF50, #45a049);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: grab;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            position: relative;
            user-select: none;
        }
        
        .qr-icon:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 15px rgba(0,0,0,0.4);
        }
        
        .qr-icon:active {
            cursor: grabbing;
            transform: scale(0.95);
        }
        
        .qr-icon.qr-dragging {
            cursor: grabbing !important;
            opacity: 0.8;
            transform: scale(1.05);
            box-shadow: 0 8px 25px rgba(0,0,0,0.5);
            z-index: ${CONFIG.zIndex + 1};
        }
        
        .qr-icon-text {
            color: white;
            font-size: 24px;
            font-weight: bold;
        }
        
        .qr-panel {
            position: absolute;
            top: ${CONFIG.iconSize + 10}px;
            right: 0;
            width: ${CONFIG.panelWidth}px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            padding: 20px;
            opacity: 0;
            transform: translateY(-10px);
            transition: opacity ${CONFIG.animationDuration}ms ease, transform ${CONFIG.animationDuration}ms ease;
            pointer-events: none;
        }
        
        .qr-panel.show {
            opacity: 1;
            transform: translateY(0);
            pointer-events: auto;
        }
        
        .qr-code-container {
            text-align: center;
            margin-bottom: 15px;
        }
        
        .qr-code {
            border: 1px solid #ddd;
            border-radius: 4px;
            display: inline-block;
        }
        
        .qr-url-display {
            font-size: 12px;
            color: #666;
            word-break: break-all;
            margin-bottom: 10px;
            padding: 5px;
            background: #f5f5f5;
            border-radius: 3px;
            width: 100%;
        }
        
        .qr-copy-button {
            width: 100%;
            padding: 8px 16px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s ease;
        }
        
        .qr-copy-button:hover {
            background: #0056b3;
        }
        
        .qr-copy-button:active {
            background: #004085;
        }
        
        .qr-copy-success {
            background: #28a745 !important;
        }
        
        .qr-dragging {
            opacity: 0.7;
            cursor: grabbing !important;
        }
        
        .qr-tooltip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            transition: opacity 0.2s ease;
            pointer-events: none;
        }
        
        .qr-icon:hover .qr-tooltip {
            opacity: 1;
        }
    `;
    
    // 创建样式元素
    function injectStyles() {
        const style = document.createElement('style');
        style.textContent = STYLES;
        document.head.appendChild(style);
    }
    
    // QR码生成器
    class QRCodeGenerator {
        constructor() {
            this.qrcodeLib = null;
            this.initQRCodeLib();
        }
        
        initQRCodeLib() {
            // 直接使用页面中的QRCode库（由content.js注入）
            if (window.QRCode) {
                this.qrcodeLib = window.QRCode;
            } else {
                // 如果库还没加载完成，等待一下
                setTimeout(() => {
                    if (window.QRCode) {
                        this.qrcodeLib = window.QRCode;
                    } else {
                    }
                }, 100);
            }
        }
        
        async generateQRCode(url) {
            try {
                // 确保库已加载
                if (!this.qrcodeLib && window.QRCode) {
                    this.qrcodeLib = window.QRCode;
                }
                
                if (!this.qrcodeLib) {
                    throw new Error('二维码库未加载');
                }
                
                // 验证URL格式
                if (!url || typeof url !== 'string') {
                    throw new Error('无效的URL');
                }
                
                // 检查URL长度（QR码有长度限制）
                if (url.length > 2048) {
                    console.warn('URL过长，可能影响二维码扫描:', url.length);
                }
                
                return new Promise((resolve, reject) => {
                    try {
                        // 创建临时容器来生成二维码
                        const tempDiv = document.createElement('div');
                        tempDiv.style.cssText = `
                            position: absolute;
                            top: -1000px;
                            left: -1000px;
                            width: 200px;
                            height: 200px;
                        `;
                        document.body.appendChild(tempDiv);
                        
                        // 使用当前库的API
                        const qr = new this.qrcodeLib(tempDiv, {
                            text: url,
                            width: 200,
                            height: 200,
                            colorDark: '#000000',
                            colorLight: '#FFFFFF',
                            correctLevel: this.qrcodeLib.CorrectLevel.M
                        });
                        
                        // 等待二维码生成完成
                        setTimeout(() => {
                            try {
                                // 查找生成的canvas或img元素
                                const canvas = tempDiv.querySelector('canvas');
                                const img = tempDiv.querySelector('img');
                                
                                if (canvas) {
                                    // 如果是canvas，克隆并确保正确显示
                                    const resultCanvas = document.createElement('canvas');
                                    resultCanvas.width = canvas.width || 200;
                                    resultCanvas.height = canvas.height || 200;
                                    resultCanvas.className = 'qr-code';
                                    
                                    // 确保显示样式
                                    resultCanvas.style.display = 'inline-block';
                                    resultCanvas.style.border = '1px solid #ddd';
                                    resultCanvas.style.borderRadius = '4px';
                                    
                                    // 复制canvas内容
                                    const ctx = resultCanvas.getContext('2d');
                                    ctx.drawImage(canvas, 0, 0);
                                    
                                    // 清理临时元素
                                    document.body.removeChild(tempDiv);
                                    resolve(resultCanvas);
                                } else if (img) {
                                    // 如果是img，转换为canvas
                                    const resultCanvas = document.createElement('canvas');
                                    resultCanvas.width = 200;
                                    resultCanvas.height = 200;
                                    resultCanvas.className = 'qr-code';
                                    
                                    // 确保显示样式
                                    resultCanvas.style.display = 'inline-block';
                                    resultCanvas.style.border = '1px solid #ddd';
                                    resultCanvas.style.borderRadius = '4px';
                                    
                                    const ctx = resultCanvas.getContext('2d');
                                    img.onload = () => {
                                        ctx.drawImage(img, 0, 0, 200, 200);
                                        // 清理临时元素
                                        document.body.removeChild(tempDiv);
                                        resolve(resultCanvas);
                                    };
                                    img.onerror = () => {
                                        document.body.removeChild(tempDiv);
                                        reject(new Error('图片加载失败'));
                                    };
                                } else {
                                    // 如果是table（旧版浏览器），转换为canvas
                                    const table = tempDiv.querySelector('table');
                                    if (table) {
                                        this.convertTableToCanvas(table, tempDiv).then(resolve).catch(reject);
                                    } else {
                                        document.body.removeChild(tempDiv);
                                        reject(new Error('未找到生成的二维码元素'));
                                    }
                                }
                            } catch (error) {
                                document.body.removeChild(tempDiv);
                                reject(new Error('处理生成的二维码失败: ' + error.message));
                            }
                        }, 100);
                        
                    } catch (error) {
                        console.error('QR码生成异常:', error);
                        reject(new Error('生成二维码异常: ' + error.message));
                    }
                });
            } catch (error) {
                console.error('二维码生成失败:', error);
                throw error;
            }
        }
        
        // 转换table为canvas（兼容旧版浏览器）
        convertTableToCanvas(table, tempDiv) {
            return new Promise((resolve, reject) => {
                try {
                    const canvas = document.createElement('canvas');
                    canvas.width = 200;
                    canvas.height = 200;
                    canvas.className = 'qr-code';
                    
                    // 确保显示样式
                    canvas.style.display = 'inline-block';
                    canvas.style.border = '1px solid #ddd';
                    canvas.style.borderRadius = '4px';
                    
                    const ctx = canvas.getContext('2d');
                    ctx.fillStyle = '#FFFFFF'; // 白色背景
                    ctx.fillRect(0, 0, 200, 200);
                    
                    const rows = table.querySelectorAll('tr');
                    const cellSize = 200 / rows.length;
                    
                    rows.forEach((row, i) => {
                        const cells = row.querySelectorAll('td');
                        cells.forEach((cell, j) => {
                            const bgColor = cell.style.backgroundColor;
                            if (bgColor && bgColor !== '#ffffff' && bgColor !== 'rgb(255, 255, 255)') {
                                ctx.fillStyle = bgColor;
                                ctx.fillRect(j * cellSize, i * cellSize, cellSize, cellSize);
                            }
                        });
                    });
                    
                    
                    // 清理临时元素
                    document.body.removeChild(tempDiv);
                    resolve(canvas);
                } catch (error) {
                    document.body.removeChild(tempDiv);
                    reject(error);
                }
            });
        }
    }
    
    // 二维码分享组件
    class QRCodeShare {
        constructor() {
            this.container = null;
            this.icon = null;
            this.panel = null;
            this.isDragging = false;
            this.dragOffset = { x: 0, y: 0 };
            this.position = CONFIG.defaultPosition;
            this.qrGenerator = new QRCodeGenerator();
            this.currentURL = window.location.href;
            this.panelVisible = false;
            this.hideTimeout = null;
            this.isHoveringIcon = false;
            this.isHoveringPanel = false;
            this.wasDragging = false; // 新增：记录是否正在拖拽
            
            this.init();
        }
        
        async init() {
            // 检查当前路径是否应该显示二维码
            if (!PathTransformer.shouldShowQRCode()) {
                return;
            }
            
            injectStyles();
            this.loadPosition();
            this.createElements();
            this.bindEvents();
            this.startURLWatcher();
        }
        
        loadPosition() {
            try {
                const saved = localStorage.getItem(CONFIG.storageKey);
                if (saved) {
                    const savedPosition = JSON.parse(saved);
                    
                    // 向后兼容：如果是旧的像素格式，转换为百分比
                    if (savedPosition.top !== undefined && savedPosition.right !== undefined) {
                        this.position = {
                            topPercent: Math.max(5, Math.min(95, (savedPosition.top / window.innerHeight) * 100)),
                            rightPercent: Math.max(5, Math.min(95, (savedPosition.right / window.innerWidth) * 100))
                        };
                        this.savePosition(); // 保存转换后的位置
                    } else if (savedPosition.topPercent !== undefined && savedPosition.rightPercent !== undefined) {
                        // 新的百分比格式
                        this.position = {
                            topPercent: Math.max(5, Math.min(95, savedPosition.topPercent)),
                            rightPercent: Math.max(5, Math.min(95, savedPosition.rightPercent))
                        };
                    } else {
                        this.position = CONFIG.defaultPosition;
                    }
                } else {
                    this.position = CONFIG.defaultPosition;
                }
                
            } catch (error) {
                console.warn('无法加载保存的位置:', error);
                this.position = CONFIG.defaultPosition;
            }
        }
        
        savePosition() {
            try {
                localStorage.setItem(CONFIG.storageKey, JSON.stringify(this.position));
            } catch (error) {
                console.warn('无法保存位置:', error);
            }
        }
        
        createElements() {
            // 创建主容器
            this.container = document.createElement('div');
            this.container.className = 'qr-share-container';
            this.container.style.position = 'fixed';
            this.container.style.top = this.position.topPercent + '%';
            this.container.style.right = this.position.rightPercent + '%';
            this.container.style.zIndex = CONFIG.zIndex;
            
            // 创建图标
            this.icon = document.createElement('div');
            this.icon.className = 'qr-icon';
            this.icon.innerHTML = `
                <div class="qr-icon-text">📱</div>
                <div class="qr-tooltip">二维码分享</div>
            `;
            // 设置拖拽相关样式
            this.icon.style.cursor = 'grab';
            this.icon.style.userSelect = 'none';
            this.container.appendChild(this.icon);
            
            // 创建面板
            this.panel = document.createElement('div');
            this.panel.className = 'qr-panel';
            this.container.appendChild(this.panel);
            
            document.body.appendChild(this.container);
            this.updateQRCode();
        }
        
        bindEvents() {
            // 图标事件
            this.icon.addEventListener('click', (e) => {
                e.preventDefault();
                if (!this.wasDragging) {
                    this.togglePanel();
                }
                this.wasDragging = false;
            });
            
            this.icon.addEventListener('mouseenter', () => {
                this.isHoveringIcon = true;
                if (!this.isDragging) {
                    this.showPanel();
                }
            });
            
            this.icon.addEventListener('mouseleave', () => {
                this.isHoveringIcon = false;
                if (!this.isDragging) {
                    this.scheduleHidePanel();
                }
            });
            
            // 面板事件
            this.panel.addEventListener('mouseenter', () => {
                this.isHoveringPanel = true;
            });
            
            this.panel.addEventListener('mouseleave', () => {
                this.isHoveringPanel = false;
                this.scheduleHidePanel();
            });
            
            // 拖拽事件 - 使用鼠标事件实现
            this.icon.addEventListener('mousedown', (e) => {
                e.preventDefault();
                this.startDrag(e);
            });
            
            // 创建事件处理器引用以便清理
            this.mouseMoveHandler = (e) => this.handleMouseMove(e);
            this.mouseUpHandler = (e) => this.handleMouseUp(e);
            this.outsideClickHandler = (e) => {
                if (!this.container.contains(e.target)) {
                    this.hidePanel();
                }
            };
            
            // 窗口resize事件处理器
            this.resizeHandler = () => this.updatePositionOnResize();
            
            // 点击外部关闭面板
            document.addEventListener('click', this.outsideClickHandler);
            
            // 监听窗口大小变化
            window.addEventListener('resize', this.resizeHandler);
            
            // 支持触摸设备
            this.icon.addEventListener('touchstart', (e) => {
                e.preventDefault();
                const touch = e.touches[0];
                this.startDrag(touch);
            });
            
            this.touchMoveHandler = (e) => {
                e.preventDefault();
                if (this.isDragging && e.touches.length > 0) {
                    this.handleMouseMove(e.touches[0]);
                }
            };
            
            this.touchEndHandler = (e) => {
                if (this.isDragging) {
                    this.handleMouseUp(e.changedTouches ? e.changedTouches[0] : e);
                }
            };
        }
        
        // 获取当前域名的uIdToken
        async getUIdToken() {
            return new Promise((resolve, reject) => {
                const requestId = Date.now().toString();
                const hostname = window.location.hostname;
                
                // 监听响应
                const handleResponse = (event) => {
                    if (event.source !== window) return;
                    
                    const payload = event.data;
                    if (!payload || typeof payload !== 'object') return;
                    
                    if (payload.action === 'uIdTokenResponse' && payload.requestId === requestId) {
                        window.removeEventListener('message', handleResponse);
                        
                        if (payload.success) {
                            resolve(payload.token);
                        } else {
                            reject(new Error('Failed to get uIdToken'));
                        }
                    }
                };
                
                window.addEventListener('message', handleResponse);
                
                // 发送请求给content script
                window.postMessage({
                    action: 'getUIdToken',
                    requestId: requestId,
                    hostname: hostname
                }, '*');
                
                // 设置超时
                setTimeout(() => {
                    window.removeEventListener('message', handleResponse);
                    reject(new Error('Timeout waiting for uIdToken'));
                }, 5000);
            });
        }
        
        // 将token附加到URL
        appendTokenToURL(url, token) {
            try {
                const urlObj = new URL(url);
                urlObj.searchParams.set('loginToken', token);
                return urlObj.toString();
            } catch (error) {
                console.error('URL解析失败:', error);
                // 如果URL解析失败，使用简单的字符串拼接
                const separator = url.includes('?') ? '&' : '?';
                return `${url}${separator}loginToken=${encodeURIComponent(token)}`;
            }
        }
        
        async updateQRCode() {
            try {
                let targetURL = window.location.href;
                
                // 首先进行路径转换
                targetURL = PathTransformer.transformURL(targetURL);
                
                // 然后尝试获取uIdToken并附加到URL
                try {
                    const token = await this.getUIdToken();
                    if (token) {
                        targetURL = this.appendTokenToURL(targetURL, token);
                    } else {
                        console.log('ℹ️ 未找到uIdToken，使用转换后的URL');
                    }
                } catch (error) {
                    console.warn('⚠️ 获取uIdToken失败，使用转换后的URL:', error);
                }
                
                this.currentURL = targetURL;
                
                const qrCode = await this.qrGenerator.generateQRCode(this.currentURL);
                this.panel.innerHTML = '';
                
                // 创建容器
                const container = document.createElement('div');
                container.className = 'qr-code-container';
                
                // 确保canvas可见
                qrCode.style.display = 'block';
                qrCode.style.margin = '0 auto';
                
                container.appendChild(qrCode);
                this.panel.appendChild(container);
                
                const urlDisplay = document.createElement('input');
                urlDisplay.className = 'qr-url-display';
                urlDisplay.value = this.currentURL;
                this.panel.appendChild(urlDisplay);
                
                // 复制按钮
                const copyButton = document.createElement('button');
                copyButton.className = 'qr-copy-button';
                copyButton.textContent = '复制链接';
                copyButton.addEventListener('click', () => this.copyURL(copyButton));
                this.panel.appendChild(copyButton);
                
            } catch (error) {
                console.error('生成二维码失败:', error);
                this.panel.innerHTML = '<div style="text-align:center;color:red;padding:20px">生成二维码失败</div>';
            }
        }
        
        async copyURL(button) {
            const originalText = button.textContent;
            const originalClass = button.className;
            
            try {
                // 禁用按钮防止重复点击
                button.disabled = true;
                button.textContent = '复制中...';
                
                // 优先使用现代Clipboard API
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(this.currentURL);
                } else {
                    // 降级方案：使用document.execCommand
                    const textArea = document.createElement('textarea');
                    textArea.value = this.currentURL;
                    textArea.style.cssText = `
                        position: fixed;
                        top: -1000px;
                        left: -1000px;
                        width: 1px;
                        height: 1px;
                        opacity: 0;
                        pointer-events: none;
                    `;
                    document.body.appendChild(textArea);
                    textArea.select();
                    textArea.setSelectionRange(0, 99999); // 兼容移动端
                    
                    const successful = document.execCommand('copy');
                    document.body.removeChild(textArea);
                    
                    if (!successful) {
                        throw new Error('execCommand复制失败');
                    }
                }
                
                // 成功反馈
                button.textContent = '已复制!';
                button.classList.add('qr-copy-success');
            } catch (error) {
                console.error('复制失败:', error);
                button.textContent = '复制失败';
                button.style.backgroundColor = '#ff6b6b';
                
                // 显示详细错误信息（开发时）
                if (console.debug) {
                    console.debug('复制错误详情:', {
                        error: error.message,
                        hasClipboardAPI: !!navigator.clipboard,
                        isSecureContext: window.isSecureContext,
                        url: this.currentURL
                    });
                }
                
            } finally {
                // 恢复按钮状态
                button.disabled = false;
                
                setTimeout(() => {
                    button.textContent = originalText;
                    button.className = originalClass;
                    button.style.backgroundColor = '';
                }, 2000);
            }
        }
        
        startURLWatcher() {
            let lastURL = window.location.href;
            let updateTimeout = null;
            
            // 防抖的URL检查函数
            const debouncedUpdateQRCode = () => {
                if (updateTimeout) {
                    clearTimeout(updateTimeout);
                }
                updateTimeout = setTimeout(() => {
                    this.updateQRCode();
                }, 300); // 300ms防抖
            };
            
            const checkURL = () => {
                const currentURL = window.location.href;
                if (currentURL !== lastURL) {
                    lastURL = currentURL;
                    
                    // 检查新路径是否符合转换规则
                    if (!PathTransformer.shouldShowQRCode()) {
                        this.hideContainer();
                        return;
                    } else {
                        this.showContainer();
                    }
                    
                    debouncedUpdateQRCode();
                }
            };
            
            // 监听popstate事件（浏览器前进后退）
            window.addEventListener('popstate', checkURL);
            
            // 监听pushstate和replacestate（SPA路由变化）
            const originalPushState = window.history.pushState;
            const originalReplaceState = window.history.replaceState;
            
            window.history.pushState = function(...args) {
                originalPushState.apply(this, args);
                setTimeout(checkURL, 100);
            };
            
            window.history.replaceState = function(...args) {
                originalReplaceState.apply(this, args);
                setTimeout(checkURL, 100);
            };
            
            // 定期检查URL变化（后备方案，降低频率）
            setInterval(checkURL, 2000);
        }
        
        showPanel() {
            if (this.hideTimeout) {
                clearTimeout(this.hideTimeout);
                this.hideTimeout = null;
            }
            this.panel.classList.add('show');
            this.panelVisible = true;
        }
        
        hidePanel() {
            this.panel.classList.remove('show');
            this.panelVisible = false;
        }
        
        togglePanel() {
            if (this.panelVisible) {
                this.hidePanel();
            } else {
                this.showPanel();
            }
        }
        
        // 显示/隐藏整个容器
        showContainer() {
            if (this.container) {
                this.container.style.display = 'block';
            }
        }
        
        hideContainer() {
            if (this.container) {
                this.container.style.display = 'none';
                this.hidePanel(); // 同时隐藏面板
            }
        }
        
        scheduleHidePanel() {
            if (this.hideTimeout) clearTimeout(this.hideTimeout);
            this.hideTimeout = setTimeout(() => {
                if (!this.isHoveringIcon && !this.isHoveringPanel) {
                    this.hidePanel();
                }
            }, 300);
        }
        
        startDrag(e) {
            e.preventDefault();
            this.isDragging = true;
            this.wasDragging = true;
            this.icon.classList.add('qr-dragging');
            this.hidePanel();
            
            // 获取初始位置
            const rect = this.container.getBoundingClientRect();
            this.dragOffset.x = e.clientX - rect.left;
            this.dragOffset.y = e.clientY - rect.top;
            
            // 添加全局事件监听器
            document.addEventListener('mousemove', this.mouseMoveHandler);
            document.addEventListener('mouseup', this.mouseUpHandler);
            document.addEventListener('touchmove', this.touchMoveHandler, { passive: false });
            document.addEventListener('touchend', this.touchEndHandler);
            
            // 改变光标样式
            document.body.style.cursor = 'grabbing';
            document.body.style.userSelect = 'none';
        }
        
        handleMouseMove(e) {
            if (!this.isDragging) return;
            
            // 计算新位置
            const newX = e.clientX - this.dragOffset.x;
            const newY = e.clientY - this.dragOffset.y;
            
            // 边界检查
            const maxX = window.innerWidth - CONFIG.iconSize;
            const maxY = window.innerHeight - CONFIG.iconSize;
            const boundedX = Math.max(0, Math.min(newX, maxX));
            const boundedY = Math.max(0, Math.min(newY, maxY));
            
            // 转换为百分比位置
            const topPercent = (boundedY / window.innerHeight) * 100;
            const rightPercent = ((window.innerWidth - boundedX - CONFIG.iconSize) / window.innerWidth) * 100;
            
            // 实时更新位置（以百分比）
            this.container.style.top = topPercent + '%';
            this.container.style.right = rightPercent + '%';
            this.container.style.left = 'auto';
            this.container.style.transform = 'none';
            
            // 更新内部位置记录
            this.position.topPercent = topPercent;
            this.position.rightPercent = rightPercent;
        }
        
        handleMouseUp(e) {
            if (!this.isDragging) return;
            
            this.isDragging = false;
            this.icon.classList.remove('qr-dragging');
            
            // 保存位置（位置已在handleMouseMove中更新）
            this.savePosition();
            
            // 清理事件监听器
            document.removeEventListener('mousemove', this.mouseMoveHandler);
            document.removeEventListener('mouseup', this.mouseUpHandler);
            document.removeEventListener('touchmove', this.touchMoveHandler);
            document.removeEventListener('touchend', this.touchEndHandler);
            
            // 恢复光标样式
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
            
            // 延迟一下再允许点击事件，避免拖拽结束时意外触发面板
            setTimeout(() => {
                this.wasDragging = false;
            }, 100);
        }
        
        // 窗口大小变化时更新位置
        updatePositionOnResize() {
            if (!this.container) return;
            
            // 确保位置在边界内
            const safeTopPercent = Math.max(5, Math.min(95, this.position.topPercent));
            const safeRightPercent = Math.max(5, Math.min(95, this.position.rightPercent));
            
            // 如果位置需要调整，更新内部记录
            if (safeTopPercent !== this.position.topPercent || safeRightPercent !== this.position.rightPercent) {
                this.position.topPercent = safeTopPercent;
                this.position.rightPercent = safeRightPercent;
                this.savePosition();
            }
            
            // 应用位置
            this.container.style.top = this.position.topPercent + '%';
            this.container.style.right = this.position.rightPercent + '%';
            this.container.style.left = 'auto';
        }
        
        destroy() {
            
            // 清除定时器
            if (this.hideTimeout) {
                clearTimeout(this.hideTimeout);
                this.hideTimeout = null;
            }
            
            // 移除事件监听器
            if (this.container) {
                // 移除拖拽事件监听器
                document.removeEventListener('mousemove', this.mouseMoveHandler);
                document.removeEventListener('mouseup', this.mouseUpHandler);
                document.removeEventListener('touchmove', this.touchMoveHandler);
                document.removeEventListener('touchend', this.touchEndHandler);
                document.removeEventListener('click', this.outsideClickHandler);
                window.removeEventListener('resize', this.resizeHandler); // 移除resize监听器
                
                // 移除容器
                this.container.remove();
                this.container = null;
                this.icon = null;
                this.panel = null;
            }
            
            // 重置状态
            this.isDragging = false;
            this.wasDragging = false;
            this.panelVisible = false;
            this.isHoveringIcon = false;
            this.isHoveringPanel = false;
        }
    }
    
    // 初始化二维码分享功能
    function initQRCodeShare() {
        // 等待页面加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initQRCodeShare);
            return;
        }
        
        try {
            window.qrCodeShare = new QRCodeShare();
        } catch (error) {
            console.error('初始化二维码分享功能失败:', error);
        }
    }
    
    // 启动初始化
    initQRCodeShare();
    
    // 监听页面可见性变化，修复iframe中的问题
    document.addEventListener('visibilitychange', () => {
        if (window.qrCodeShare && document.visibilityState === 'visible') {
            // 检查当前URL是否应该显示二维码
            if (PathTransformer.shouldShowQRCode()) {
                window.qrCodeShare.showContainer();
                window.qrCodeShare.updateQRCode();
            } else {
                window.qrCodeShare.hideContainer();
            }
        }
    });
    
    // 暴露API供其他脚本调用
    window.qrCodeShareAPI = {
        showQRCode: () => window.qrCodeShare?.showPanel(),
        hideQRCode: () => window.qrCodeShare?.hidePanel(),
        updateQRCode: () => window.qrCodeShare?.updateQRCode(),
        getCurrentURL: () => window.qrCodeShare?.currentURL,
        destroy: () => window.qrCodeShare?.destroy()
    };
    
    // 监听来自content script的启用/禁用消息
    window.addEventListener('message', function(event) {
        if (event.source !== window) return;
        
        const message = event.data;
        if (!message || typeof message !== 'object') return;
        
        if (message.action === 'enableQRCode') {
            if (!window.qrCodeShare) {
                initQRCodeShare();
            } else {
                // 如果已存在，重新显示
                if (window.qrCodeShare.container) {
                    window.qrCodeShare.container.style.display = 'block';
                }
            }
        } else if (message.action === 'disableQRCode') {
            if (window.qrCodeShare) {
                window.qrCodeShare.destroy();
                window.qrCodeShare = null;
            }
        }
    });
    
})();
